﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using spring.stp6.db.provider;
using spring.stp6.db.provider.Entity;
using spring.stp6.web.Models;

using System.Linq.Dynamic;
using System.Linq.Expressions;
using log4net;
using System.Reflection;

namespace spring.stp6.web.Controllers
{
    public class CustomerController : BaseController
    {  
        private ILog logger = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        Expression<Func<CustomerEntity, bool>> searchExpress;

        //
        // GET: /Customer/
        public ActionResult Index(int start, int limit, string searchkey, FormCollection collection)
        {            
            JsonData<CustomerEntity> data;

            try 
            {
                searchExpress = u=>u.status!=1;

                using (var ctx = new SalesManDBContent())
                {

                    if (!String.IsNullOrEmpty(Request.QueryString["name"]))
                    {
                        searchExpress = searchExpress.And(u => u.name.Contains(Request.QueryString["name"]));
                        
                    }
                    else if (!String.IsNullOrEmpty(Request.QueryString["tel"]))
                    {
                        searchExpress = searchExpress.And(u => u.tele.Contains(Request.QueryString["tel"]));
                    }
                    else if (!String.IsNullOrEmpty( searchkey))
                    {
                        searchExpress = u => (u.name.Contains(searchkey) || u.mobile.Contains(searchkey) || u.position.Contains(searchkey))&&(u.status!=1);
                     
                    }
                    List<CustomerEntity> lst = ctx.Customers.Where(searchExpress)
                                                            .Select(u => u)
                                                            .OrderByDescending(u=>u.id)
                                                            .Skip(start)
                                                            .Take(limit)
                                                            .ToList<CustomerEntity>();

                   data = new JsonData<CustomerEntity>(lst.Count, lst);                                       
                }
            }
            catch (Exception ex)
            {
                logger.Error("Get /Customer/ ", ex);
                data = new JsonData<CustomerEntity>();
            }
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Customer/Details/5

        public ActionResult Details(int id)
        {
            return View();
        }

        //
        // GET: /Customer/Create
        [HttpPost]
        public ActionResult Create(CustomerEntity e)
        {
            JsonMsg msg = new JsonMsg();
            try
            {
                using (var ctx = new SalesManDBContent())
                {
                    if (e.id > 0)
                    {
                       var selEntity= ctx.Customers.SingleOrDefault<CustomerEntity>(u => u.id == e.id);

                       selEntity.city = e.city;
                       selEntity.email = e.email;
                       selEntity.mobile = e.mobile;
                       selEntity.name = e.name;
                       selEntity.position = e.position;
                       selEntity.privilege = e.privilege;
                       selEntity.province = e.province;
                       selEntity.qq = e.qq;
                       selEntity.remarks = e.remarks;
                       selEntity.sex = e.sex;
                       selEntity.tele = e.tele;

                       ctx.SaveChanges(); 
                    }
                    else {
                        e.createDate = DateTime.Now;
                        ctx.Customers.Add(e);
                        ctx.SaveChanges();                    
                    }
                }
                msg = new JsonMsg(true, "客户信息保存成功！");
            }
            catch (Exception ex) {
                logger.Error("POST: /Customer/Create", ex);
                msg = new JsonMsg(false, "客户信息保存失败！");
            }
            return Json(msg);
        } 
        
        // POST: /Customer/Delete
        [HttpPost]
        public ActionResult Delete(string ids)
        {
            JsonMsg msg = new JsonMsg();
            try
            {
                // TODO: Add delete logic here
               String[] idList= ids.Split(new string[]{","},StringSplitOptions.RemoveEmptyEntries);
               int num = 0;
               using (var ctx = new SalesManDBContent())
               {
                   foreach (var m in idList)
                   {
                       num = Int32.Parse(m);
                       var selEntity = ctx.Customers.SingleOrDefault<CustomerEntity>(u => u.id == num);
                       if (selEntity != null) {

                           selEntity.status = 1;//标示删除
                           ctx.SaveChanges();
                       }
                   }                   
               }
               msg = new JsonMsg(true, "客户信息删除成功！");
            }
            catch
            {
                msg = new JsonMsg(false, "客户信息删除失败！");
               
            }
            return Json(msg);
        }
    }
}
